package com.gu.myviewmodel.services

import android.content.Context
import android.view.ViewDebug.FlagToString
import androidx.room.*

@Database(entities = [Car::class], version = 1, exportSchema = false)
abstract class CarDatabase : RoomDatabase() {
    abstract fun carDao(): CarDao

    companion object {
        private const val DATABASE_NAME = "car_database.db"
        private var instance: CarDatabase? = null

        fun getInstance(context: Context): CarDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context.applicationContext).also { instance = it }
            }
        }

        private fun buildDatabase(context: Context): CarDatabase {
            val dir = "${context.filesDir}/${DATABASE_NAME}"
            return Room.databaseBuilder(context, CarDatabase::class.java, dir).build()
        }
    }
}

@Dao
interface CarDao {
    @Query("SELECT * FROM cars_table ORDER BY id")
    suspend fun getCars(): List<Car>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(cars: List<Car>)

    @Query("DELETE FROM cars_table")
    suspend fun deleteOld()

    @Query("SELECT * FROM cars_table")
    suspend fun getCarsNoOrder(): List<Car>
}

@Entity(tableName = "cars_table")
class Car(val brand: String, val name: String, val cost: Long, val engine: Int, val horsepower: Int, @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val carId: Int? = null) {
    override fun toString(): String {
        return "[$brand,$name,$cost,$engine,$horsepower,$carId]"
    }
}
